/*
-----------------------------------------------------------------------------
This source file is part of Glare3D
(The Graphics Library Abstract Rendering Engine)
For the latest info, see http://code.google.com/p/glare3d/

Copyright (c) 2012 Fuse-Software (tm)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "glare.gles2.RenderWindow.h"
#include "glare.core.RenderWindow.h"

#if GLARE_PLATFORM == GLARE_PLATFORM_WIN32
#	include "glare.core.Win32Window.h"
#elif GLARE_PLATFORM == GLARE_PLATFORM_ANDROID
#	include "glare.core.AndroidWindow.h"
#endif

#include "glare.gles2.Driver.h"

namespace Glare {

	GLES2RenderWindow::GLES2RenderWindow(GLES2Driver* driver, PlatformWindow* platform_window) 
		: RenderWindow(platform_window)
		, _driver(driver)
		, _egl_display(EGL_NO_DISPLAY)
		, _egl_surface(EGL_NO_SURFACE)
		, _egl_context(EGL_NO_CONTEXT)
	{
		_driver->WriteLog("Created GLES2 RenderWindow", LMT_Debug);
	}

	GLES2RenderWindow::~GLES2RenderWindow()
	{
		_driver->WriteLog("Destroying GLES2 RenderWindow", LMT_Debug);

		// TODO: check if we should use eglDestroySurface & eglDestroyContext instead
		// since this will possible destroy every RenderWindow's egl handles
		eglMakeCurrent(_egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);

		if (_egl_context != EGL_NO_CONTEXT)
		{
			eglDestroyContext(_egl_display, _egl_context);
			_egl_context = EGL_NO_CONTEXT;
			_driver->WriteLog("Destroyed GLES2 Context", LMT_Debug);
		}

		if (_egl_surface != EGL_NO_SURFACE)
		{
			eglDestroySurface(_egl_display, _egl_surface);
			_egl_surface = EGL_NO_SURFACE;
			_driver->WriteLog("Destroyed GLES2 Surface", LMT_Debug);
		}

		if (_egl_display != EGL_NO_DISPLAY)
		{
			eglTerminate(_egl_display);
			_egl_display = EGL_NO_DISPLAY;
			_driver->WriteLog("Destroyed GLES2 Display", LMT_Debug);
		}

		_driver->WriteLog("Destroyed GLES2 RenderWindow", LMT_Debug);
	}

	void GLES2RenderWindow::InitializeImpl()
	{
		_driver->WriteLog("Initializing GLES2 RenderWindow", LMT_Debug);

		EGLNativeWindowType	egl_window	= 0;

#if GLARE_PLATFORM == GLARE_PLATFORM_WIN32
		PlatformWindow* window = GetPlatformWindow();

		Win32Window* w32_window = static_cast<Win32Window*>(window);
		egl_window = w32_window->GetWindowHandle();

		HDC hdc = GetDC(egl_window);

		if (!hdc)
			throw Exception("failed to create GLES2 device context");

		_egl_display = eglGetDisplay(hdc);

#elif GLARE_PLATFORM == GLARE_PLATFORM_ANDROID
		PlatformWindow* window = GetPlatformWindow();

		AndroidWindow* droid_window = static_cast<AndroidWindow*>(window);
		egl_window = droid_window->GetNativeWindow();
#endif

		if (_egl_display == EGL_NO_DISPLAY)
			_egl_display = eglGetDisplay((EGLNativeDisplayType)EGL_DEFAULT_DISPLAY);

		EGLint iMajorVersion, iMinorVersion;
		if (!eglInitialize(_egl_display, &iMajorVersion, &iMinorVersion))
			throw Exception("eglInitialize() failed.");

		_driver->WriteLog("EGL initialized", LMT_Debug);

		eglBindAPI(EGL_OPENGL_ES_API);
		EGL_CHECK_ERROR;
		_driver->WriteLog("GLES2 API bound", LMT_Debug);

		//const EGLint egl_config_attributes[] =
		//{
		//	EGL_LEVEL,				0,
		//	EGL_SURFACE_TYPE,		EGL_WINDOW_BIT,
		//	EGL_RENDERABLE_TYPE,	EGL_OPENGL_ES2_BIT,
		//	EGL_NATIVE_RENDERABLE,	EGL_FALSE,
		//	EGL_DEPTH_SIZE,			EGL_DONT_CARE,
		//	EGL_NONE
		//};

		const EGLint egl_config_attributes[] =
		{
			EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
			EGL_RENDERABLE_TYPE,	EGL_OPENGL_ES2_BIT,
			EGL_BLUE_SIZE, 8,
			EGL_GREEN_SIZE, 8,
			EGL_RED_SIZE, 8,
			EGL_NONE
		};

		EGLConfig egl_config;
		EGLint num_configs;
		if (!eglChooseConfig(_egl_display, egl_config_attributes, &egl_config, 1, &num_configs) || (num_configs != 1))
			throw Exception("eglChooseConfig() failed.");

		_driver->WriteLog("GLES2 config chosen", LMT_Debug);

#if GLARE_PLATFORM == GLARE_PLATFORM_ANDROID
		EGLint format;

		eglGetConfigAttrib(_egl_display, egl_config, EGL_NATIVE_VISUAL_ID, &format);
		_driver->WriteLog("GLES2 buffer format queried", LMT_Debug);

		ANativeWindow_setBuffersGeometry(egl_window, 0, 0, format);
		_driver->WriteLog("GLES2 ANativeWindow_setBuffersGeometry", LMT_Debug);
#endif

		_egl_surface = eglCreateWindowSurface(_egl_display, egl_config, egl_window, NULL);
		_driver->WriteLog("Created GLES2 WindowSurface", LMT_Debug);

		if (_egl_surface == EGL_NO_SURFACE)
		{
			eglGetError(); // Clear error
			_egl_surface = eglCreateWindowSurface(_egl_display, egl_config, NULL, NULL);
			_driver->WriteLog("Warning: Created GLES2 default WindowSurface", LMT_Debug);
		}
		EGL_CHECK_ERROR;

		EGLint context_attributes[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
		_egl_context = eglCreateContext(_egl_display, egl_config, NULL, context_attributes);
		EGL_CHECK_ERROR;

		_driver->WriteLog("Created GLES2 Context", LMT_Debug);

		eglMakeCurrent(_egl_display, _egl_surface, _egl_surface, _egl_context);
		EGL_CHECK_ERROR;

		_driver->WriteLog("Made GLES2 Context current", LMT_Debug);
	}

	void GLES2RenderWindow::SetFullscreenImpl(const bool& fullscreen)
	{
		throw Exception("The method or operation is not implemented.");
	}

	void GLES2RenderWindow::Present()
	{
		eglSwapBuffers(_egl_display, _egl_surface);
		glFinish();
	}

	void GLES2RenderWindow::SetOptionImpl(const string& name, const string& value)
	{
	}

	RenderTarget::Interface* GLES2RenderWindow::_GetInterface()
	{
		return this;
	}

	Driver* GLES2RenderWindow::GetDriver() const
	{
		return _driver;
	}

	void GLES2RenderWindow::MakeCurrent() const
	{
		eglMakeCurrent(_egl_display, _egl_surface, _egl_surface, _egl_context);
		EGL_CHECK_ERROR;
	}
}
